

#include "tcp.h"
#include "unp.h"

namespace wakefieldq {

CTcp::CTcp(int port)
{
	this->servport = port;
}

CTcp::~CTcp()
{

}
int CTcp::open_listen()
{
	listenfd = socket(AF_INET, SOCK_STREAM, 0);
	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(servport);

	bind(listenfd, (SA* )&servaddr, sizeof(servaddr));
	listen(listenfd, LISTENQ);

	return listenfd;
}

int CTcp::receive()
{
	memset(&cliaddr, 0, sizeof(cliaddr));
	clilen = sizeof(cliaddr);
	return accept(listenfd, (SA*)&cliaddr, &clilen);
}

int CTcp::connectto(char* str_ipaddr)
{
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(servport);

	inet_pton(AF_INET, str_ipaddr, &servaddr.sin_addr);
	servlen = sizeof(servaddr);

	connect(sockfd, (SA*)&servaddr, servlen);
	return 1;
}

int CTcp::get_cliaddr(struct sockaddr_in* addr)
{
	memcpy(addr, &cliaddr, sizeof(cliaddr));
	return clilen;
}

int CTcp::get_servaddr(struct sockaddr_in* addr)
{
	addr = &servaddr;
	return servlen;
}

void CTcp::Close(int connfd)
{
	close(connfd);
}

char* CTcp::sock_ntop(const struct sockaddr* sa, socklen_t salen, char* buf)
{
	char	portstr[8];
	CPrint::msg("AF_INET:%d,sa_family:%d",AF_INET,sa->sa_family);
	switch(sa->sa_family)
	{
	case AF_INET:
		struct sockaddr_in *sin = (struct sockaddr_in*)sa;
		if(inet_ntop(AF_INET, &sin->sin_addr, buf, 128) == NULL)
			return NULL;
		if(ntohs(sin->sin_port) != 0)
			snprintf(portstr, sizeof(portstr), ":%d", ntohs(sin->sin_port));
		strcat(buf, portstr);
	}
	return buf;

}
}